package com.ste.server.command;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ste.domain.Client;
import com.ste.server.Server;

public class Logon {
	public static final String regexp = "35=A\\|49=(.*)";
	private Server server;
	private Command command;
	private String clientName;

	public Logon(Server server, Command command) {
		this.server = server;
		this.command = command;
		parseMessage(command.getMessage());
	}

	private void parseMessage(String message) {
		Matcher matcher = Pattern.compile(regexp).matcher(command.getMessage());
		if (matcher.matches()) {
			clientName = matcher.group(1);
		}
	}

	public String execute() {
		synchronized (server.getClients()) {
			for (Client client : server.getClients()) {
				if (clientName.equals(client.getName())) {
					return "35=5|58=client with the same ID is already connected";
				}
			}
			command.getClient().setName(clientName);
			return "35=A";
		}
	}
}
